package com.kedacom.demo.modularity.feed;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.kedacom.demo.modularity.email.EmailService;
import com.kedacom.demo.modularity.message.InstantMessage;
import com.kedacom.demo.modularity.message.XMPPMessageGateway;

@Service("feedService")
public class FeedServiceImpl implements FeedService {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected Map<Long, Feed> feeds = new LinkedHashMap<Long, Feed>();

	@Resource(name = "emailService")
	private EmailService emailService;

	@Resource(name = "xmppMessageGateway")
	private XMPPMessageGateway xmppMessageGateway;

	public FeedServiceImpl() {
		init();
	}

	// @PostConstruct
	public void test() {
		emailService.send();
	}

	protected void init() {
		feeds.put(1L, new Feed(1L, "Hello world", "1"));
		feeds.put(2L, new Feed(2L, "给大家推荐一个有用的工具dropbox， 很好的云存储你的文档，便于在办公室、家或者移动办公时共享文档。 性能优于微软的skydrive，而且可以跨平时使用。",
				"3"));
		feeds.put(3L, new Feed(3L, "都说程序员内向 可是为代码而吵架的时候能量值直逼小区大妈。躺枪的自觉下面排队~", "1"));
		feeds.put(4L, new Feed(4L, "据说升级到新版QQ的童鞋都疯了……怀着一颗好奇心，还是不敢点啊…有那么不好用吗？", "3"));
		feeds.put(5L, new Feed(5L, "树莓派求组团购买", "2"));
	}

	public void publish(Feed feed) {
		Assert.notNull(feed);
		Assert.notNull(feed.getId());
		Assert.hasText(feed.getBody());
		Assert.hasText(feed.getCreatedBy());

		feeds.put(feed.getId(), feed);
		logger.debug("publish feed {} success.", feed);

		// send xmpp message
		xmppMessageGateway.send(new InstantMessage("1999", "newFeed", "{'type':'newFeed',count:1}", "admin@test.com",
				"huangrong@test.com"));

		// suppose that we need send an email to whom has been reminded.
		// emailService.queue(new Email(1999L, "您在致友微博有新的未读消息", "您有2条@提到你的消息",
		// "zhiyou@test.com", "huangrong@test.com"));
	}

	public Feed get(Long id) {
		Assert.notNull(id);
		Feed feed = feeds.get(id);
		logger.debug("get feed {} by id {}.", feed, id);

		return feed;
	}

	public List<Feed> listAll() {
		logger.debug("list all feeds.");
		return new ArrayList<Feed>(feeds.values());
	}

	public void setXmppMessageGateway(XMPPMessageGateway xmppMessageGateway) {
		this.xmppMessageGateway = xmppMessageGateway;
	}

	public void setEmailService(EmailService emailService) {
		this.emailService = emailService;
	}

}
